package application.graph;

import java.util.Random;

import application.Node;

/** @author Krystian */

public class GraphGenerator {

	private static Random r;

	/** Funkcja generujaca graf */
	public static Node[] generate(int nodes, int edges, int colors,
			int minColorForNode, int maxColorForNode) throws Exception {

		Node[] graph = new Node[nodes + 1];

		r = new Random();

		for (int i = 1; i < graph.length; i++) {

			graph[i] = new Node();

			int nodeColors = 0;

			if (maxColorForNode > minColorForNode) {
				nodeColors = r.nextInt(maxColorForNode - minColorForNode + 1)
						+ minColorForNode;
			} else if (maxColorForNode == minColorForNode) {
				nodeColors = minColorForNode;
			} else {
				throw new Exception(
						"Min > Max (liczba kolorów dla wierzcholka)");
			}

			for (int j = 0; j < nodeColors; j++) {

				int maxCounter = 10;
				do {

					if (--maxCounter < 0) {
						break;
					}

					int randColor = r.nextInt(colors);

					if (!graph[i].hasPossibleColor(randColor)) {
						graph[i].insertColor(randColor);
						break;
					}

				} while (true);
			}
		}

		for (int e = 0; e < edges; e++) {

			int maxCounter = 20;

			do {

				if (--maxCounter < 0) {
					break;
				}

				int nodeId1 = r.nextInt(nodes) + 1;
				int nodeId2 = nodeId1;

				do {
					nodeId2 = r.nextInt(nodes) + 1;
				} while (nodeId1 == nodeId2);

				if (!graph[nodeId1].hasAdjacentNode(nodeId2)) {
					graph[nodeId1].insertAdjacentNode(nodeId2);
					graph[nodeId2].insertAdjacentNode(nodeId1);
					break;
				}

			} while (true);

		}

		return graph;
	}
}
